﻿(function ($) {

    $.fn.chatform = function (options) {

        // Create some defaults, extending them with any options that were provided
        var settings = $.extend({
            serviceUrl: 'http://www.google.com',
            width: '200px',
            height: '300px',
            token: 'UhajQAxcv8TPOSuNjGWAgugR0Y75SoZUPxAgDpJIApECJ4KXRkMFDIrCrXs7ezGZLtWdoGaIBZo1'
        }, options);

        var proxy;
        var serviceUrl = settings.serviceUrl;
        var token = settings.token;
        var username;
        var secret;
        var contact;
        var email;
        var phone;

        var chat_form;
        var chat_registercontrol;
        var chat_registersubmit;
        var chat_messagescontrol;

        var chat_messagesgrid;
        var chat_messageinput;

        try {
            proxy = $(this).ServiceProxy(serviceUrl);
        }
        catch (e) {
            alert("no proxy service found");
        }

        return this.each(function () {

            /////////////////////////CONTAINER///////////////////////////////////
            chat_form = $("<div class='call_container flexcroll'></div>");
            chat_form.css("width", settings.width);
            chat_form.css("height", settings.height);
            chat_registercontrol = $("<div class='w_container'></div>");
            chat_messagescontrol = $("<div class='m_container'></div>");
            chat_messagesgrid = $("<div class='w_all_area '>Messages....</div>");
            secret = token;
            ///////////////////////////////////////////////////////////
            username = $("<div contenteditable='true' class='w_from_text'>name</div>");
            contact = $("<div contenteditable='true' class='w_from_text'>contact</div>");
            email = $("<div contenteditable='true' class='w_email_text'>email@domain.com</div>");
            phone = $("<div contenteditable='true' class='w_phone_text'>000-000-0000</div>");
            //////////////////////////////////////////////////////////
            usernamelbl = $("<div  class='w_from_lbl'>Name:</div>");
            contactlbl = $("<div  class='w_from_lbl'>Contact:</div>");
            emaillbl = $("<div  class='w_from_lbl'>Email:</div>");
            phonelbl = $("<div  class='w_from_lbl'>Phone:</div>");
            //////////////////////////////////////////////////////////
            var lay = $("<table/>");

            var rtr = $("<tr/>");
            var rtrc1 = $("<td/>").append(usernamelbl);
            var rtrc2 = $("<td/>").append(username);
            rtr.append(rtrc1);
            rtr.append(rtrc2);
            lay.append(rtr);

            ////////////////////

            var ftr = $("<tr/>");
            var ftrc1 = $("<td/>").append(emaillbl);
            var ftrc2 = $("<td/>").append(email);
            ftr.append(ftrc1);
            ftr.append(ftrc2);
            lay.append(ftr);

            //                    /////////////////////

            //                    var ztr = $("<tr/>");
            //                    var ztrc1 = $("<td/>").append(phonelbl);
            //                    var ztrc2 = $("<td/>").append(phone);
            //                    ztr.append(ztrc1);
            //                    ztr.append(ztrc2);
            //                    lay.append(ztr);

            /////////////////////////

            chat_registercontrol.append(lay);

            chat_registersubmit = $("<div class='w_from_btn'> Register </div>").button().click(function () {
                var name = username.text();
                var contact = email.text();
                var data = $.param({ token: token, user: name, email: contact });
                proxy.CallService("GET", "GetToken", data, OnGetToken, OnError);

            });

            chat_registercontrol.append(chat_registersubmit);
            chat_form.append(chat_registercontrol);

            /////////////////////////////////////////CALL/////////////////////////////////////

            chat_messageinput = $("<div class='w_msg_area' contenteditable='true'> Your Name : </div>").keyup(function (k) {
                var key = k.keyCode;
                if (key == 13) {
                    var msg = chat_messageinput.text();
                    var name = username.text();
                    var contact = email.text();

                    var data = $.param({ token: token, user: name, contact: contact, message: msg });
                    proxy.CallService("GET", "SetMessage", data, function (result) {
                        //OnAddMessage(name,  contact, result);
                        GetMessages(name, contact);
                        ClearMessageInput();
                    }, OnError);
                }
            });

            chat_messagescontrol.append(chat_messagesgrid);
            chat_messagescontrol.append(chat_messageinput);

            chat_form.append(chat_messagescontrol);

            $(this).append(chat_form);

            chat_registercontrol.show();
            chat_messagescontrol.hide();


            //////////////////////////////////

            function OnGetToken(message) {
                this.token = message;
                token = message;
                chat_registercontrol.hide();
                chat_messagescontrol.show();
            }
            function ClearMessageGrid() {
                chat_messagesgrid.html("");
            }
            function ClearMessageInput() {
                chat_messageinput.html("");
            }
            function AddMessage(user, contact, id, message) {
                var m = $("<div><span class='m_user_lbl'> " + user + "</span> :&gt; " + message + "</div>");
                m.attr("msgid", id);
                chat_messagesgrid.append(m);
            }
            function OnAddMessage(user, contact, message) {
                AddMessage(user, contact, 0, message);
            }
            function OnError(xhr, w, e, method) {

                if (this.dataType == "jsonp") {

                    resultObject = result.GetEmployeeResult;
                    var string = result.Name + " \n " + result.Address;
                    alert(string);
                }

                alert(xhr.responseText);
                if (xhr.responseText) {
                    var err = xhr.responseText;
                    if (err)
                        error(err);
                    else
                        error({ Message: "Unknown server error." })
                }
                return;
            }
            function GetMessages(user, contact) {
                var data = $.param({ token: token, user: user, contact: contact });
                proxy.CallService("GET", "GetMessages", data, function (result) {
                    ClearMessageGrid();
                    $(result).each(function (i) {
                        AddMessage(this.FromContact, this.FromContact, this.ID, this.Message);
                    });
                }, OnError);
            }
        });
    };
})(jQuery);